/**
 * 安卓白金英雄坛制作组 <br>
 * 文件名：PaymentDialog.java <br>
 * 创建时间：2015-4-10 下午4:07:07 <br>
 * 所属项目：GmudEX <br>
 * @author 12548 <br>
 */
package lostland.gmud.exv2.ui.meta;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Environment;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.Toast;

import com.bmob.pay.tool.BmobPay;
import com.bmob.pay.tool.PayListener;
import com.orhanobut.logger.Logger;
import com.tencent.mid.api.MidService;
import com.tencent.stat.StatService;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Properties;

import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;
import lostland.gmud.exv2.Game;
import lostland.gmud.exv2.Gmud;
import lostland.gmud.exv2.Gmud.PaymentStatus;
import lostland.gmud.exv2.R;
import lostland.gmud.exv2.community.GmudUser;
import lostland.gmud.exv2.data.GmudMap;
import lostland.gmud.exv2.expand.GmudPayment;

/**
 * 类名：PaymentDialog <br>
 * 说明：注册对话框
 *
 * @author 12548
 */
public class PaymentDialog extends Dialog implements android.view.View.OnClickListener {

	private Window mWindow;
	ProgressDialog dialog;

	String name;
	String body;

	BmobPay bmobPay;

	double price;

	Game game;

	GmudPayment payment = new GmudPayment();


	public PaymentDialog(double price) {
		super(Game.getInstance());

		this.game = Game.getInstance();
		this.price = price;

		payment.setMoney(String.valueOf(price));

		mWindow = getWindow();
		mWindow.setBackgroundDrawable(new ColorDrawable(0));
		mWindow.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
		WindowManager.LayoutParams lp = mWindow.getAttributes();
		lp.gravity = Gravity.CENTER;
		lp.dimAmount = 0.0001f;
		mWindow.setAttributes(lp);
		setCanceledOnTouchOutside(false);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		mWindow.setContentView(R.layout.dialog_pay);
		bmobPay = new BmobPay(game);

		findViewById(R.id.btnPayByAli).setOnClickListener(this);
		findViewById(R.id.btnPayByWx).setOnClickListener(this);

		findViewById(R.id.btnAbortPay).setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				dismiss();
			}
		});
	}


	/* （非 Javadoc）
	 * @see android.app.Dialog#cancel()
	 */
	@Override
	public void cancel() {

	}


	// 调用微信支付
	void payByWeiXin() {
		showDialog("正在获取订单...");

		bmobPay.payByWX(price, name, body, new PayListener() {

			// 因为网络等原因,支付结果未知(小概率事件),出于保险起见稍后手动查询
			@Override
			public void unknow() {
				Toast.makeText(game, "支付结果未知,请稍后手动查询", Toast.LENGTH_SHORT).show();
				onUnknow();
				hideDialog();
			}

			// 支付成功,如果金额较大请手动查询确认
			@Override
			public void succeed() {

				onSucceed();
				hideDialog();
			}

			// 无论成功与否,返回订单号
			@Override
			public void orderId(String orderId) {
				// 此处应该保存订单号,比如保存进数据库等,以便以后查询
				saveOrderId(orderId);
				showDialog("获取订单成功!请等待跳转到支付页面~");
			}

			// 支付失败,原因可能是用户中断支付操作,也可能是网络原因
			@Override
			public void fail(int code, String reason) {

				// 当code为-2,意味着用户中断了操作
				// code为-3意味着没有安装BmobPlugin插件
				if (code == -3) {
					new AlertDialog.Builder(game)
							.setMessage(
									"你尚未安装支付插件，是否安装插件或改用支付宝支付？")
							.setPositiveButton("安装",
									new DialogInterface.OnClickListener() {

										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											installBmobPayPlugin("BmobPayPlugin.apk");
										}
									})
							.setNegativeButton("支付宝支付",
									new DialogInterface.OnClickListener() {

										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											showDialog("正在获取订单...");

											bmobPay.pay(price, name, body, new PayListener() {

												// 因为网络等原因,支付结果未知(小概率事件),出于保险起见稍后手动查询
												@Override
												public void unknow() {
													Toast.makeText(game, "支付结果未知,请稍后手动查询", Toast.LENGTH_SHORT).show();

													hideDialog();

													onUnknow();
												}

												// 支付成功,如果金额较大请手动查询确认
												@Override
												public void succeed() {

													onSucceed();

													hideDialog();
												}

												// 无论成功与否,返回订单号
												@Override
												public void orderId(String orderId) {
													// 此处应该保存订单号,比如保存进数据库等,以便以后查询

													saveOrderId(orderId);
													showDialog("获取订单成功!请等待跳转到支付页面~");
												}

												// 支付失败,原因可能是用户中断支付操作,也可能是网络原因
												@Override
												public void fail(int code, String reason) {
													Toast.makeText(game, "支付中断!", Toast.LENGTH_SHORT)
															.show();

													if (!payment.getOrderID().getValue().isEmpty()) {
														Gmud.paymentData.payments.remove(payment.getOrderID().getValue());
														Gmud.paymentData.saveLocal();
													}
													hideDialog();
												}
											});
										}
									}).create().show();
				} else {
					Toast.makeText(game, "支付中断!",
							Toast.LENGTH_SHORT).show();
				}
				if (!payment.getOrderID().getValue().isEmpty()) {
					Gmud.paymentData.payments.remove(payment.getOrderID().getValue());
					Gmud.paymentData.saveLocal();
				}
				hideDialog();
			}
		});
	}


	void showDialog(String message) {
		if (dialog == null) {
			dialog = new ProgressDialog(getContext());
			dialog.setCancelable(false);
		}
		dialog.setMessage(message);
		dialog.show();
	}

	void hideDialog() {
		if (dialog != null && dialog.isShowing()) {
			dialog.dismiss();
		}
	}

	void installBmobPayPlugin(String fileName) {
		try {
			InputStream is = getContext().getAssets().open(fileName);
			File file = new File(Environment.getExternalStorageDirectory()
					+ File.separator + fileName);
			file.createNewFile();
			FileOutputStream fos = new FileOutputStream(file);
			byte[] temp = new byte[1024];
			int i = 0;
			while ((i = is.read(temp)) > 0) {
				fos.write(temp, 0, i);
			}
			fos.close();
			is.close();

			Intent intent = new Intent(Intent.ACTION_VIEW);
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			intent.setDataAndType(Uri.parse("file://" + file),
					"application/vnd.android.package-archive");
			Game.getInstance().startActivity(intent);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	/* （非 Javadoc）
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	@Override
	public void onClick(View v) {
		name = ((EditText) findViewById(R.id.etPayNickname)).getText().toString();
		body = "MID：" + MidService.getMid(game) + "  Saying：" + ((EditText) findViewById(R.id.etPaySaying)).getText().toString();

		if (body.length() > 250) {
			body = body.substring(0, 250); //太长会报错。。。
		}
		payment.setName(name);
		payment.setBody(body);
		payment.setMid(MidService.getMid(game));
		if (GmudUser.getInstance() != null) {
			payment.setCommunityUsername(GmudUser.getInstance().getUsername());
		}

		if (v.getId() == R.id.btnPayByAli) {
			showDialog("正在获取订单...");

			bmobPay.pay(price, name + "的购买", body, new PayListener() {

				// 因为网络等原因,支付结果未知(小概率事件),出于保险起见稍后手动查询
				@Override
				public void unknow() {
					Toast.makeText(game, "支付结果未知", Toast.LENGTH_SHORT).show();

					hideDialog();

					onUnknow();
				}

				// 支付成功,如果金额较大请手动查询确认
				@Override
				public void succeed() {

					onSucceed();

					hideDialog();
				}

				// 无论成功与否,返回订单号
				@Override
				public void orderId(String orderId) {
					// 此处应该保存订单号,比如保存进数据库等,以便以后查询

					saveOrderId(orderId);
					showDialog("获取订单成功!请等待跳转到支付页面~");
				}

				// 支付失败,原因可能是用户中断支付操作,也可能是网络原因
				@Override
				public void fail(int code, String reason) {
					Toast.makeText(game, "支付中断!", Toast.LENGTH_SHORT)
							.show();

					if (!payment.getOrderID().getValue().isEmpty()) {
						Gmud.paymentData.payments.remove(payment.getOrderID().getValue());
						Gmud.paymentData.saveLocal();
					}
					hideDialog();
				}
			});
		} else if(v.getId() == R.id.btnPayByWx) {
			payByWeiXin();
		}
	}


	/**
	 * @param orderId
	 */
	private void saveOrderId(String orderId) {

		payment.setOrderID(orderId);

		Properties prop = new Properties();
		prop.setProperty("money", payment.getMoney().getValue());
		prop.setProperty("call_name", payment.getName());
		prop.setProperty("body", payment.getBody());
		prop.setProperty("community_username", payment.getCommunityUsername());
		prop.setProperty("orderid", payment.getOrderID().getValue());
		prop.setProperty("mid", payment.getMid().getValue());

		StatService.trackCustomKVEvent(game, "ev_pay_orderid", prop);


		Gmud.paymentData.payments.put(orderId, payment);
		Gmud.paymentData.saveLocal();

		payment.save(game, new SaveListener() {

			@Override
			public void onFailure(int arg0, String arg1) {
			}

			@Override
			public void onSuccess() {
				Logger.i(payment.getObjectId());
			}
		});

	}


	/**
	 *
	 */
	private void onUnknow() {
		if (Gmud.paymentData.paymentStatus == PaymentStatus.TRIAL ||
				Gmud.paymentData.paymentStatus == PaymentStatus.TRIAL2) {
			Gmud.paymentData.paymentStatus = PaymentStatus.ZERO;
		}
		Gmud.paymentData.saveLocal();
		game.popToRootScreen();
		dismiss();

		Gmud.maps[1].setEvent(12, 8, -1);
		Gmud.maps[1].setWalkable(12, 8, GmudMap.MP_WALKABLE);
	}


	/**
	 *
	 */
	private void onSucceed() {

		Properties prop = new Properties();
		prop.setProperty("money", payment.getMoney().getValue());
		prop.setProperty("call_name", payment.getName());
		prop.setProperty("body", payment.getBody());
		prop.setProperty("community_username", payment.getCommunityUsername());
		prop.setProperty("orderid", payment.getOrderID().getValue());
		prop.setProperty("mid", payment.getMid().getValue());

		StatService.trackCustomKVEvent(game, "ev_pay_success", prop);

		payment.setPaymentStatus("SUCCESS");
		Toast.makeText(game, "支付成功，非常感谢您的支持！", Toast.LENGTH_SHORT).show();
		payment.update(game, new UpdateListener() {

			@Override
			public void onFailure(int arg0, String arg1) {
				Logger.e(arg0 + arg1);
			}

			@Override
			public void onSuccess() {
				// TODO 自动生成的方法存根

			}
		});
		Gmud.paymentData.paymentStatus = PaymentStatus.PAID;
		Gmud.paymentData.saveLocal();
		game.setRectangleStone(name);
		game.popToRootScreen();
		dismiss();

		Gmud.maps[1].setEvent(12, 8, -1);
		Gmud.maps[1].setWalkable(12, 8, GmudMap.MP_WALKABLE);

		Gmud.maps[2].setEvent(10, 7, -1);
		Gmud.maps[2].setWalkable(10, 7, GmudMap.MP_WALKABLE);
	}

}
